/**
 * 
 */
package de.datenwalze.winterpokal.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import de.datenwalze.winterpokal.json.WPEntry;
import de.datenwalze.winterpokal.json.WPJsonResponse;

/**
 * This class is used to do a http request to the winterpokal server and get the
 * json based response.
 * 
 * @author Jens Helweg
 * 
 */
public class WPHttpConnection {
	private static final int SOCKET_TIMEOUT = 45000;

	private final static String IBC_SERVER_MTB = "http://winterpokal.mtb-news.de/api/";
	private final static String IBC_SERVER_RENNRAD = "http://winterpokal.rennrad-news.de/api/";
	private final static String INTERFACE_VERSION = "v1";
	private final static String REQUEST_ARG = "550"; // dusiemas team id :-)

	private final static String API_KEY_DUSIEMA = "TF47GLNALDHYKUO8SSNJNUZH9DEHD9AOBIEU";

	public static WPJsonResponse sendEntry(WPEntry wpEntry) {
		WPJsonResponse jsonResponse = null;
		URL url = null;
		try {
			WPGetParameter getParameters = new WPGetParameter();
			url = new URL(constructUrlStringTeams("entries", "add",
					getParameters));

			StringBuilder sb = doRequestAndReturnJson(url, wpEntry);

			Log.d("JSON", "JSON parsing starts...");
			Gson gson = new GsonBuilder().create();
			jsonResponse = gson.fromJson(sb.toString(), WPJsonResponse.class);

			if (jsonResponse != null) {
				Log.d("JSON", "JSON has been parsed.");
			}

		} catch (MalformedURLException e) {
			Log.d(WPHttpConnection.class.toString(),
					String.format("URL: %s is not mal formed!", url), e);
		}

		return jsonResponse;
	}

	public static WPJsonResponse getHttpResult() {

		WPJsonResponse jsonResponse = null;

		URL url = null;
		try {
			WPGetParameter getParameters = new WPGetParameter();
			getParameters.setTeamId(REQUEST_ARG);
			
			url = new URL(
					constructUrlStringTeams("teams", "get", getParameters));

			StringBuilder sb = doRequestAndReturnJson(url, null);

			Log.d("JSON", "JSON parsing starts...");
			Gson gson = new GsonBuilder().create();
			jsonResponse = gson.fromJson(sb.toString(), WPJsonResponse.class);

			if (jsonResponse != null) {
				Log.d("JSON", "JSON has been parsed.");
			}

		} catch (MalformedURLException e) {
			Log.d(WPHttpConnection.class.toString(),
					String.format("URL: %s is not mal formed!", url), e);
		}

		return jsonResponse;
	}

	public static StringBuilder doRequestAndReturnJson(URL url, WPEntry wpEntry) {
		StringBuilder sb = new StringBuilder();

		// If this next line is not set the second call to url will fail!
		System.setProperty("http.keepAlive", "false");

		try {
			HttpURLConnection http = (HttpURLConnection) url.openConnection();

			http.setConnectTimeout(SOCKET_TIMEOUT);
			http.setReadTimeout(SOCKET_TIMEOUT);

			http.setRequestProperty("api-token", API_KEY_DUSIEMA);

			if (wpEntry != null) {
				Gson gson = new GsonBuilder().create();

				http.setRequestMethod("POST");
				http.setDoInput(true);
				http.setDoOutput(true);
				// Send request
				DataOutputStream outStream = new DataOutputStream(
						http.getOutputStream());
				outStream.writeBytes(gson.toJson(wpEntry));
				outStream.flush();
				outStream.close();
			}

			InputStream ins = http.getInputStream();
			InputStreamReader isr = new InputStreamReader(ins);
			BufferedReader in = new BufferedReader(isr);

			String inputLine;

			while ((inputLine = in.readLine()) != null) {
				sb.append(inputLine);
			}

			in.close();
			isr.close();
			ins.close();
			http.disconnect();

		} catch (SocketTimeoutException ste) {
			Log.d(WPHttpConnection.class.toString(), String.format(
					"TimeoutException occured after: %d !", SOCKET_TIMEOUT),
					ste);
		} catch (IOException e) {
			Log.d(WPHttpConnection.class.toString(), String.format(
					"Could not execute request for url: %s !", url), e);
		}

		return sb;
	}

	/**
	 * This method will construct the URL String for web service request.
	 * 
	 * @param getParameter
	 * @return String the String that can be used as a URL.
	 */
	private static String constructUrlStringTeams(String type, String method,
			WPGetParameter getParameter) {
		StringBuilder urlString = new StringBuilder();

		urlString.append(IBC_SERVER_MTB);
		urlString.append("/");
		urlString.append(INTERFACE_VERSION);
		urlString.append("/");
		urlString.append(type);
		urlString.append("/");
		urlString.append(method);
		if (getParameter != null && getParameter.getTeamId() != null
				&& getParameter.getTeamId().length() > 0) {
			urlString.append("/");
			urlString.append(REQUEST_ARG);
		}
		urlString.append(".json");

		// HashMap<String, String> allGetParameters = getParameters
		// .getAllGetParameters();
		//
		// if (!allGetParameters.isEmpty()) {
		// urlString.append("?");
		// }
		//
		// for (Iterator<String> iterator =
		// allGetParameters.keySet().iterator(); iterator
		// .hasNext();) {
		// String parameterKey = iterator.next();
		// urlString.append(parameterKey);
		// urlString.append("=");
		// urlString.append(allGetParameters.get(parameterKey));
		// if (iterator.hasNext()) {
		// urlString.append("&");
		// }
		// }
		//

		return urlString.toString();

	}
}
